<template>
  <div id="app" style="font-size: 26px; font-weght: bold; margin: 30px 0">
    <!-- <header class="header">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="品牌名称:">
          <el-input
            v-for="(item, index) in topInputList"
            :key="index"
            v-model="item.text"
            :placeholder="item.title"
            class="top-input"
          ></el-input>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search"
          >搜索</el-button
        >
        <el-button type="primary" icon="el-icon-plus" @click="handleEdit"
          >添加</el-button
        >
      </el-form>
     
    </header> -->

    <!-- <el-table v-loading="loading" :data="tableData" max-height="600" border fit>
      <el-table-column show-overflow-tooltip prop="id" label="ID" width="80">
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="name"
        label="品牌名称"
        width=""
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="sort"
        label="类型"
        width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.type == 1 ? "水" : "材料" }}
        </template>
      </el-table-column>
      <el-table-column label="LOGO" show-overflow-tooltip width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.aavatar.length > 0"
            style="width: 30px; height: 30px"
            :src="scope.row.aavatar[0]"
            :preview-src-list="scope.row.aavatar"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="utime"
        label="更新时间"
        width="180"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="sort"
        label="排序"
        width="100"
      >
      </el-table-column>

      <el-table-column label="操作" show-overflow-tooltip width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" @click="deleteBrand(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination> -->
    <div class="imgBox">
      <p>营业执照</p>
      <el-image
        :lazy="lazy"
        style="width: 600px; height: 400px"
        :src="imgHeader + url"
        fit="fit"
      ></el-image>
      <el-button type="primary" @click="handleEdit">编辑</el-button>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="outerVisible"
      :before-close="handleClosediaLoding"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="formLabelAlign"
        :rules="rules"
        ref="ruleForm"
      >
        <!-- <div class="oneLine">
          <el-form-item label="品牌名称" prop="name">
            <el-input
              maxlength="15"
              show-word-limit
              v-model="formLabelAlign.name"
            ></el-input>
          </el-form-item>
        </div> -->
        <div class="oneLine">
          <el-form-item label="LOGO" prop="atavar">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFile"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
                :on-change="fileChange"
              >
                <el-button size="mini" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
              <el-image
                style="width: 100px; height: 100px"
                :src="formLabelAlign.atavar"
                fit="cover"
              ></el-image>
            </div>
          </el-form-item>
        </div>
        <!-- <div class="oneLine">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="formLabelAlign.sort"
              oninput="if(value.length>4)value=value.slice(0,4)"
              type="number"
              style="width: 100px"
              :min="0"
            ></el-input>
          </el-form-item>
        </div> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeVisible('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadFilec,
  brandList,
  setBrand,
  addBrand,
  deleteBrand,
  deleteSort,
  pingtaishezhi,
  saveSet,
} from "../../../utils/api";
import { compressImage } from "../../../assets/js/compressImage";
export default {
  data() {
    //这里存放数据
    return {
      url: "",
      lazy: true,
      token: sessionStorage.getItem("token"),
      topInputList: [{ title: "品牌名称", text: "" }],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      total: 0,
      limit: 10,
      loading: true,
      outerVisible: false,
      formLabelAlign: {
        name: "",
        sort: "",
        atavar: "",
        avatar: "",
        id: "",
        type: 1,
      },
      imgHeader: this.Global.imgHeader,

      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      bianjiFlag: false,
      rules: {
        name: [
          { required: true, message: "请输入品牌名称", trigger: "change" },
        ],
        atavar: [{ required: true, message: "请上传图片", trigger: "change" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "change" }],
      },
      dialogTitle: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    handleEdit() {
      this.outerVisible = true;
      this.formLabelAlign.atavar = this.imgHeader + this.url;
      // console.log("url", this.formLabelAlign.avatar);
    },
    // 获取列表数据
    searchUser() {
      this.loading = true;
      pingtaishezhi(this.token)
        .then((res) => {
          if (res.data.status) {
            let zizhi = res.data.data.find((item) => item.key == "tbj_zizhi");
            this.url = zizhi.value;
            // console.log(this.url);
            // this.total = res.data.data.count;
            // this.tableData.forEach((item) => {
            //   if (item.img) {
            //     item.image = item.img;
            //     item.img = "https://bjsf.bjsky.top" + item.img;
            //     console.log(item.img);
            //   }
            // });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            let timer = setTimeout(() => {
              this.$message.error(res.data.msg);
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err.msg);
        });
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let img = "";
          img = this.formLabelAlign.avatar
            ? this.formLabelAlign.avatar
            : this.formLabelAlign.atavar
            ? this.url
            : "";
          // console.log("img", img);
          // let regExp = /^0*[1-9]\d*|0$/;
          // if (!regExp.test(this.formLabelAlign.sort)) {
          //   this.$message({
          //     message: "排序要为正整数",
          //     type: "warning",
          //   });
          //   return;
          // }
          let list = { tbj_zizhi: img };
          saveSet(JSON.stringify(list), this.token).then((res) => {
            if (res.data.status) {
              this.$message({
                message: "保存成功",
                type: "success",
                // onClose: (res) => {},
              });
              this.outerVisible = false;
              this.searchUser();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    closeVisible(formName) {
      this.$refs[formName].resetFields();
      this.outerVisible = false;
      this.formLabelAlign.atavar = "";
      // this.formLabelAlign.id = "";
      // this.formLabelAlign.name = "";
      // this.formLabelAlign.sort = "";
    },
    handleClosediaLoding() {
      this.$refs.ruleForm.resetFields();
      this.outerVisible = false;
      this.formLabelAlign.atavar = "";
      // this.formLabelAlign.id = "";
      // this.formLabelAlign.name = "";
      // this.formLabelAlign.sort = "";
    },
    // 选中的用户

    // handleSizeChange(val) {
    //   this.limit = val;
    //   // console.log(`每页 ${val} 条`);
    //   this.brandList(
    //     this.token,
    //     this.currentPage,
    //     this.limit,
    //     this.topInputList[0].text,
    //     1
    //   );
    // },
    // 第几页
    // handleCurrentChange(val) {
    //   this.currentPage = val;
    //   this.brandList(
    //     this.token,
    //     this.currentPage,
    //     this.limit,
    //     this.topInputList[0].text,
    //     1
    //   );
    // },
    // 获取用户信息
    // brandList(token, page, limit, name, type) {
    //   this.loading = true;
    //   brandList(token, page, limit, name, type).then((res) => {
    //     // console.log(res.data)
    //     if (res.data.status) {
    //       this.tableData = res.data.data.data;
    //       this.total = res.data.data.count;
    //       this.tableData.forEach((item) => {
    //         item.aavatar = [];
    //         if (item.logo) {
    //           item.aavatar.push("https://bjsf.bjsky.top" + item.logo);
    //         }
    //       });
    //       let timer = setTimeout(() => {
    //         this.loading = false;
    //         clearTimeout(timer);
    //       }, 400);
    //     } else {
    //       if (res.data.msg == "token失效,请重新进行登录") {
    //         this.$router.push("/login");
    //       }
    //       this.loading = false;
    //       this.$message.error(res.data.msg);
    //       // let timer = setTimeout(()=>{
    //       //   this.$message.error('错误，请刷新');
    //       // },5000)
    //     }
    //   });
    // },

    // search() {
    //   this.brandList(
    //     this.token,
    //     this.currentPage,
    //     this.limit,
    //     this.topInputList[0].text,
    //     1
    //   );
    // },

    // 删除
    // deleteBrand(index, row) {
    //   // console.log(row)
    //   this.$confirm("确定删除品牌吗", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       deleteBrand(this.token, row.id, "").then((res) => {
    //         // console.log(res)
    //         if (res.data.status == true) {
    //           this.$message({
    //             type: "success",
    //             message: "删除成功!",
    //             onClose: (res) => {
    //               this.brandList(
    //                 this.token,
    //                 this.currentPage,
    //                 this.limit,
    //                 this.topInputList[0].text,
    //                 1
    //               );
    //             },
    //           });
    //         } else {
    //           this.$message.error(res.data.msg);
    //         }
    //       });
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: "info",
    //         message: "已取消删除",
    //       });
    //     });
    // },
    // handleEdit(index, row) {
    //   this.bianjiFlag = false;
    //   this.outerVisible = true;
    //   this.dialogTitle = "创建品牌";
    //   console.log(this.formLabelAlign);
    //   if (row) {
    //     this.bianjiFlag = true;
    //     this.dialogTitle = "编辑品牌";
    //     this.formLabelAlign.name = row.name;
    //     this.formLabelAlign.sort = row.sort;
    //     this.formLabelAlign.atavar = row.aavatar[0];
    //     this.formLabelAlign.id = row.id;
    //     this.formLabelAlign.avatar = row.logo;
    //     this.formLabelAlign.type = row.type;
    //   }
    // },
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },
    //上传文件的事件
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFilec(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.formLabelAlign.atavar = res.data.data.weburl;
            this.formLabelAlign.avatar = res.data.data.saveurl;
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      // uploadFilec(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     // console.log(res)
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.formLabelAlign.atavar = res.data.data.weburl;
      //     this.formLabelAlign.avatar = res.data.data.saveurl;
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.toAdd();
    this.searchUser();
    // this.brandList(
    //   this.token,
    //   this.currentPage,
    //   this.limit,
    //   this.topInputList[0].text,
    //   1
    // );
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped >
#app {
  width: 100%;
}

/* .header {
  background: white !important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
}

.top-input {
  width: 150px;
  margin-right: 20px;
}

.el-table th.el-table__cell > .cell {
  text-align: center;
}

.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}

.el-table .cell.el-tooltip {
  text-align: center;
}

.el-table {
  margin: 20px 0;
}

.el-checkbox:last-of-type {
  margin-left: 0;
}

.oneLine {
  display: flex;
  justify-content: space-between;
}

.el-dialog__wrapper .el-dialog {
  width: 35%;
}

.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}

.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
} */
.imgBox {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.imgBox p {
  font-size: 18px;
  margin-bottom: 20px;
  margin-top: 20px;
}
.imgBox .el-button {
  margin-top: 10px;
  width: 100px;
}
</style>
